/* eslint-disable prettier/prettier */
import React, { useEffect, useState } from 'react';
import styles from './styles';
import {DeviceEventEmitter,View,Text,Modal,ImageBackground,Image, TouchableHighlight, TouchableOpacity } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Loginpage from '../loginPage/Loginpage';
import success from '../loginPage/Loginpage';
import Buybookpage from '../loginPage/Buybookpage';
const Login = ({route,navigation}) => {

  const [loginstate,SetLoginstate] = useState<Boolean>(false);
    const [backgroundTransparent, setBackgroundTransparent] = useState('transparent');
    const [modalVisible, setModalVisible] = useState(false);
    const [shopmodalVisible, setshopModalVisible] = useState(false);
    const [success,setSuccess] = useState<boolean>(true);
    const [fresh,setfresh] = useState<boolean>(false);
      const showResultDialog = () => {
        if (loginstate === false){
          setModalVisible(true);
          setSuccess(true);
          setBackgroundTransparent('rgba(0, 0, 0, 0.15)');  } else {
            setModalVisible(true);
            setSuccess(false);
            setBackgroundTransparent('rgba(0, 0, 0, 0.15)');
        }

      };
      const showShopDialog = () => {
        console.log("显示shop界面");
          setshopModalVisible(true);
      };
      useEffect(() => {
        console.log(modalVisible);
      },[ modalVisible]);


      useEffect(() => {
        const checkToken = async () => {
          try {
            const token = await AsyncStorage.getItem('token');
            if (token) {
              SetLoginstate(true); // Token exists, user is logged in
            } else {
              SetLoginstate(false); // Token doesn't exist, user is not logged in
            }
          } catch (error) {
            console.error('Failed to fetch token from AsyncStorage:', error);
          }
        };
        checkToken();
        const listener = DeviceEventEmitter.addListener('login', (message) => {
          console.log('监听到！');
          console.log(message);
          setModalVisible(!message);
        });
        const listener2 = DeviceEventEmitter.addListener('token', (m) => {
          console.log('recive token！');
          console.log(m);
          // storeToken(m);
        });
        const listener3 = DeviceEventEmitter.addListener('refreshlogin', (m) => {
          console.log('LoginPagerefresh');
          console.log(m);
          SetLoginstate(m);
          setModalVisible(false);
        });
        console.log('初始化监听');
        return () => {
            if (listener) {
                listener.remove();
            }
            if (listener2){
              listener2.remove();
            }
            if (listener3){
              listener3.remove();
            }
        };
    }, []); // 空依赖数组确保这个effect只在组件挂载后运行一次
    return (
        // <ImageBackground
        // resizeMode="stretch"
        // style={[styles.container, { backgroundColor: backgroundTransparent }]}
        // source={require('../../src/image/bg_study_top.png')}>

          <View style={[styles.container]}>
            <Image source={require('../../src/image/bg_study_top.png')} style={styles.Image} />
              <View style={ styles.buttons}>
              <TouchableOpacity style={styles.button} onPress={showResultDialog}>
              <Image source={require('../../src/image/UI/person_my.png')} style={styles.ui} />
              {loginstate ? <Text style={styles.text}>已登录</Text> : <Text style={styles.text}>未登录</Text>}
            </TouchableOpacity>
            <TouchableOpacity style={styles.button} onPress={() => {console.log('购买');showShopDialog();}}>
            <Image source={require('../../src/image/UI/buy_book.png')} style={styles.ui} />
                    <Text style={styles.text}>购买</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.button} onPress={() =>navigation.navigate('contact')}>
            <Image source={require('../../src/image/UI/person_contact.png')} style={styles.ui} />
                    <Text style={styles.text}>联系我们</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.button} onPress={() => navigation.navigate('privacy')}>
            <Image source={require('../../src/image/UI/person_private.png')} style={styles.ui} />
                    <Text style={styles.text}>隐私政策</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.button} onPress={() => navigation.navigate('contract')}>
            <Image source={require('../../src/image/UI/person_contract.png')} style={styles.ui} />
                    <Text style={styles.text}>用户协议</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.button} onPress={() =>navigation.navigate('report')}>
            <Image source={require('../../src/image/UI/person_report.png')} style={styles.ui} />
                    <Text style={styles.text}>举报</Text>
            </TouchableOpacity>
              </View>
            <Modal animationType="fade"
            transparent={true}
    visible={modalVisible || shopmodalVisible}
    onRequestClose={() => { setModalVisible(!modalVisible);}}
    style={{ backgroundColor: 'rgba(0, 0, 0, 0.5)', alignItems: 'center', borderRadius: 20, justifyContent:'center',position:'absolute',width:'100%',height:'100%'}}
    >
<View style={{  backgroundColor: 'rgba(0, 0, 0, 0.5)',alignItems: 'center', borderRadius: 20, justifyContent:'center',position:'absolute',width:'100%',height:'100%'}} />
    </Modal>
<View style={styles.modalContainer}>
  <Loginpage
    visible={modalVisible}
    success={success}
    navigation={navigation}
    onClose={() => { setModalVisible(!modalVisible);}}
  />
  <Buybookpage
    visible={shopmodalVisible}
    success={success}
    navigation={navigation}
    onClose={() => { setshopModalVisible(!shopmodalVisible);}}
  />
</View>
        </View>
    );

};

export default Login;
